package net.zjitc.controller;

import net.zjitc.common.ResultMessage;
import net.zjitc.pojo.Cart;
import net.zjitc.pojo.User;
import net.zjitc.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @Author admin
 * @Date 2019/4/16 11:41
 */
@Controller
public class CartController {
    @Autowired
    CartService cartService;

    /**
     * 添加购物车，使用ajax
     * @param cart
     * @param request
     * @return
     */
    @RequestMapping("/addProductToCart")
    @ResponseBody
    public ResultMessage addProductToCart(Cart cart,
                                          HttpServletRequest request){
        //获取当前用户信息
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        cart.setUid(user.getId());

        int resultCount = cartService.addProductToCart(cart);
        if (resultCount>0){
            return ResultMessage.createSuccessMessage("添加购物车成功");
        }
        return ResultMessage.createErrorMessage("添加购物车失败");
    }


    @RequestMapping("/myCart")

    public String myCart(Model model,HttpServletRequest request){
        //获取当前用户信息
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        List<Cart> cartList = cartService.findCartsByUid(user.getId());
        model.addAttribute("cartList",cartList);
        return "/client/cart.jsp";
    }


    @RequestMapping("/updateQuantity")
    @ResponseBody
    public ResultMessage updateCart(@RequestBody Cart cart,
                                    HttpServletRequest request){
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        cart.setUid(user.getId());
        int resultCount = cartService.updateCart(cart);
        return ResultMessage.createSuccessMessage("修改成功");
    }


    @RequestMapping("/deleteCartItem")
    @ResponseBody
    public ResultMessage deleteCartItem(Integer id) {
        int resultCount = cartService.deleteCartItemById(id);
        if (resultCount > 0) {
            return ResultMessage.createSuccessMessage("商品已经成功从购物车移除");
        }
        return ResultMessage.createErrorMessage("商品移除失败");
    }

}
